<?php

/*
 * To change this template, choose Tools | Templates
* and open the template in the editor.
*/

class HT_Model_administrator_models_commune extends Zend_Db_Table {//ten class fai viet hoa

	protected $_db;

	public function __construct() {
		$this->_name = "commune";
		$this->_db = Zend_Registry::get('dbMain');
		parent::init();
	}
	
	public function addData($data){
		$this->insert($data);
		return $this->getMaxId();
	}
	
	public function getMaxId(){
		$sql = "SELECT MAX(commune_id) FROM commune";
		return  (int)$this->_db->fetchOne($sql);
	}
	public function getCommune($communeId,$filter = array()) {
		$sql = "SELECT cmm.commune_id, cmm.commune_name, dt.district_id, dt.district_name, pv.province_id, pv.province_name
				FROM commune cmm
				INNER JOIN district dt ON cmm.district_id = dt.district_id
				INNER JOIN province pv ON dt.province_id = pv.province_id
				WHERE cmm.commune_id= ".(int)$communeId;
		return $this->_db->fetchRow($sql);
	}
	public function getListCommune_nb($filter = array()) {
		$sqlPlus = $this->getListCommune_sqlPlus($filter);
		$sql = "SELECT COUNT(cmm.commune_id)
				FROM commune cmm
				INNER JOIN district dt ON cmm.district_id = dt.district_id
				INNER JOIN province pv ON dt.province_id = pv.province_id
				WHERE 1=1 $sqlPlus";
		return $this->_db->fetchOne($sql);
	}
	public function getListCommune($start=0,$size = 10,$filter = array()) {
		$sqlPlus = $this->getListCommune_sqlPlus($filter);
		$sql = "SELECT cmm.commune_id, cmm.commune_name, dt.district_id, dt.district_name, pv.province_id, pv.province_name
				FROM commune cmm
				INNER JOIN district dt ON cmm.district_id = dt.district_id
				INNER JOIN province pv ON dt.province_id = pv.province_id
				WHERE 1=1 $sqlPlus ORDER BY cmm.commune_name LIMIT $start,$size";
		return $this->_db->fetchAll($sql);
	}
	
	private function getListCommune_sqlPlus($filter){
		$sqlPlus = null;
		foreach($filter as $key => $val){
			$key = trim($key);
			$val = trim($val);
			switch($key){
				case 'keyword':
					if($val) $sqlPlus .= " AND (cmm.commune_name LIKE '%$val%' OR cmm.commune_code LIKE '%$val%' OR dt.district_name LIKE '%$val%' OR pv.province_name LIKE '%$val%') ";
					break;
				case 'province_id':
					if((int)$val >0) $sqlPlus .= " AND pv.province_id = ".(int)$val;
					break;
				case 'district_id':
					if((int)$val >0) $sqlPlus .= " AND dt.district_id = ".(int)$val;
					break;
			}
		}
		return $sqlPlus;
	}
	
}

?>
